package com.rb.util.sms;

import java.io.IOException;
import java.util.Properties;

import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpException;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.commons.httpclient.methods.PostMethod;


public class SMSUtil implements SMSInterface {

	private Properties properties;
	private String charset, uid, key;

	public SMSUtil(Properties properties) {
		this.properties = properties;
		charset = properties.getProperty("charset");
		uid = properties.getProperty("uid");
		key = properties.getProperty("key");
	}

	@Override
	public boolean send(String phone, String msg) {
		boolean result = false;

		HttpClient client = new HttpClient();
		PostMethod post = new PostMethod(properties.getProperty("url"));
		post.addRequestHeader("Content-Type", "application/x-www-form-urlencoded;charset=" + charset);// 在头文件中设置转码
		NameValuePair[] data = { new NameValuePair("Uid", uid), new NameValuePair("Key", key),
				new NameValuePair("smsMob", phone), new NameValuePair("smsText", msg) };
		post.setRequestBody(data);
		try {
			client.executeMethod(post);
			Header[] headers = post.getResponseHeaders();
			int statusCode = post.getStatusCode();
			System.out.println("statusCode:" + statusCode);
			for (Header h : headers) {
				System.out.println(h.toString());
			}
			String res = new String(post.getResponseBodyAsString().getBytes(charset));
			System.out.println(res); // 打印返回消息状态

			post.releaseConnection();
			result = true;
		} catch (HttpException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return result;

	}

}
